import {
  login,
  usersInfo,
  changePwd,
  getGames,
  ordersPages,
  ordersLottery,
  ordersOdds,
  ordersRaw,
  ordersBalanced,
  ordersHistory,
  bet,
  gameRule,
  period,
  gameAccount,
  lastResult,
  lastOrder,
  result,
} from '@/api/member'
import { setToken, removeToken, setUserName } from '@/utils/auth'

const member = {
  state: {
    isMobile: false, // 是否手机界面
    info: {}, // 会员信息
    gameSelected: null,
    pageSelected: null,
    games: null,
    gamePeriod: null, // 游戏当期信息
    gameAccount: null, // 游戏当前账号信息
    pages: null, // 游戏选页
    lottery: null,
    odds: null,
    bets: {}, // 选定的投注项目
    raw: null,
    balanced: null,
    history: null,
    rule: null,
    lastGameResult: null,
    lastGameOrder: null,
    listaAtivePane: [], // 列表页面active panel
    Lotteryss: null,
    firstBets: {}, // 第一次投注后返回的投注信息，用来给用户确定
  },

  mutations: {
    // 设定
    MEMBER_SET_IS_MOBILE: (state, payload) => {
      state.isMobile = payload
    },
    // 选定游戏
    MEMBER_SELECT_GAME: (state, payload) => {
      state.gameSelected = payload
    },
    // 选定分页
    MEMBER_SELECT_PAGE: (state, payload) => {
      state.pageSelected = payload
    },
    MEMBER_SET_INFO: (state, payload) => {
      state.info = payload
    },
    MEMBER_SET_GAME_ACCOUNT: (state, payload) => {
      state.gameAccount = payload
    },
    MEMBER_SET_GAMES: (state, payload) => {
      state.games = payload
    },
    MEMBER_SET_PERIOD: (state, payload) => {
      state.gamePeriod = payload
    },
    MEMBER_SET_RULE: (state, payload) => {
      state.rule = payload
    },
    MEMBER_SET_PAGES: (state, payload) => {
      state.pages = payload
    },
    MEMBER_SET_LOTTERY: (state, item) => {
      state.lottery = formatLottery(item)
      console.log('获取下注数据', state.lottery)
    },
    MEMBER_SET_ODDS: (state, payload) => {
      state.odds = payload
    },
    MEMBER_SET_BETS: (state, payload) => {
      state.bets = payload
    },
    MEMBER_SET_RAW: (state, payload) => {
      state.raw = payload
    },
    MEMBER_SET_BALANCED: (state, payload) => {
      state.balanced = payload
    },
    MEMBER_SET_HISTORY: (state, payload) => {
      state.history = payload
    },
    MEMBER_SET_PANEL: (state, payload) => {
      state.listaAtivePane = payload
    },
    MEMBER_SET_LAST_RESULT: (state, payload) => {
      state.lastGameResult = payload
    },
    MEMBER_SET_LAST_ORDER: (state, payload) => {
      state.lastGameOrder = payload
    },
    // 第一次下注后返回的下注信息
    MEMBER_FIRST_BETS: (state, item) => {
      // 修改返回的数据，为返回的数据添加新字段checked，即全部默认被选中
      console.log('MEMBER_FIRST_BETS', item)
      for (let i = 0; i < item.valid_bets.length; i++) {
        item.valid_bets[i]['checked'] = true
      }
      state.firstBets = item
    },
    // 修改下注后返回的下注信息中的单选框对应的值item为对象，保存了{check：false， key：index（下注信息的索引值）}
    MEMBER_UPDATE_FIRST_BETS_FROM: (state, item) => {
      console.log('MEMBER_UPDATE_FIRST_BETS_FROM', item)
      state.firstBets.valid_bets[item.key].amount = item.value
      let total_amount = 0 // eslint-disable-line no-unused-vars
      for (const key in state.firstBets.valid_bets) {
        if (state.firstBets.valid_bets[key].checked) {
          total_amount += parseInt(state.firstBets.valid_bets[key].amount)
        }
      }
      state.firstBets.total_bets_amount = parseInt(total_amount)
    },
    // 修改下注后返回的下注信息中下注组数及下注金额
    MEMBER_UPDATE_FIRST_BETS_COUNT: (state, item) => {
      if (item.check) {
        state.firstBets.total_bets++
      } else {
        state.firstBets.total_bets--
      }
      // state.firstBets.valid_bets[item.key].amount = item.value
      let total_amount = 0  // eslint-disable-line no-unused-vars
      for (const key in state.firstBets.valid_bets) {
        if (state.firstBets.valid_bets[key].checked) {
          total_amount += parseInt(state.firstBets.valid_bets[key].amount)
        }
      }
      state.firstBets.total_bets_amount = parseInt(total_amount)
    },
    // 修改下注后返回的下注信息中的单选框对应的值item为对象，保存了{check：false， key：index（下注信息的索引值）}
    MEMBER_UPDATE_FIRST_BETS: (state, item) => {
      state.firstBets.valid_bets[item.key].checked = item.check
    },
    // 开奖结果
    LOTTERY_RESULE_AA: (state, payload) => {
      state.Lotteryss = payload
    },
  },

  actions: {
    // 登录
    async MemberLogin({ commit }, payload) {
      return new Promise((resolve, reject) => {
        login(payload)
          .then(data => {
            if (data && data.token) {
              setToken(data.token)
              setUserName(payload.username)
              commit('MEMBER_SET_IS_MOBILE', Boolean(payload.isMobile)) // 设置手机界面
            }
            resolve(data)
          })
          .catch(error => {
            reject(error)
          })
      })
    },

    // 获取用户信息
    async MemberGetInfo({ commit, state }, payload) {
      if (payload.username === state.info.username) {
        // 如果是全局账号,不重复请求数据
        return state.info
      }
      return new Promise((resolve, reject) => {
        usersInfo({ username: payload.username })
          .then(data => {
            if (payload.set) {
              // 保存
              commit('MEMBER_SET_INFO', data)
            }
            resolve(data)
          })
          .catch(error => {
            reject(error)
          })
      })
    },

    // 获取当前游戏的账号信息
    async MemberGameAccount({ commit, state }, payload) {
      return new Promise((resolve, reject) => {
        gameAccount({ game: state.gameSelected})
          .then(data => {
            commit('MEMBER_SET_GAME_ACCOUNT', data)
            resolve(data)
          })
          .catch(error => {
            reject(error)
          })
      })
    },

    // 获取当前游戏的当期信息
    async MemberGamePeriod({ commit, state }, payload) {
      return new Promise((resolve, reject) => {
        period({ game: state.gameSelected, '_': parseInt(Date.now() / 1000) })
          .then(data => {
            commit('MEMBER_SET_PERIOD', data)
            resolve(data)
          })
          .catch(error => {
            reject(error)
          })
      })
    },

    // 修改密码
    async MemberChangePwd({ commit }, payload) {
      return new Promise((resolve, reject) => {
        changePwd(payload)
          .then(data => {
            resolve(data)
          })
          .catch(error => {
            reject(error)
          })
      })
    },

    // 前端 登出
    async MemberFedLogOut({ commit }) {
      return new Promise(resolve => {
        commit('MEMBER_SET_INFO', '')
        removeToken()
        resolve()
      })
    },

    // 获取当前会员可投注的彩种列表
    async MemberGames({ commit, state }, payload) {
      return new Promise((resolve, reject) => {
        getGames(payload)
          .then(data => {
            commit('MEMBER_SET_GAMES', data)
            commit('MEMBER_SELECT_GAME', Object.keys(data)[0])
            resolve(data)
          })
          .catch(error => {
            reject(error)
          })
      })
    },

    // 获取指定彩种的页面类型
    async MemberOrdersPages({ commit, state }, payload) {
      return new Promise((resolve, reject) => {
        ordersPages({ game: state.gameSelected})
          .then(data => {
            commit('MEMBER_SET_PAGES', data)
            commit('MEMBER_SELECT_PAGE', Object.keys(data)[0])
            resolve(data)
          })
          .catch(error => {
            reject(error)
          })
      })
    },

    // //获取页面下注数据
    // async MemberOrdersLottery(commit, payload) {
    //   formatLottery(payload)
    //   commit('MEMBER_SET_LOTTERY', payload)
    // },

    // 获取当前游戏赔率
    async MemberOrdersOdds({ commit, state }, payload) {
      return new Promise((resolve, reject) => {
        ordersOdds(payload)
          .then(data => {
            console.log('当前游戏赔率----', data)
            commit('MEMBER_SET_ODDS', data)
            resolve(data)
          })
          .catch(error => {
            reject(error)
          })
      })
    },

    // 获取未结明细
    async MemberOrdersRaw({ commit, state }, payload) {
      return new Promise((resolve, reject) => {
        ordersRaw(payload)
          .then(data => {
            commit('MEMBER_SET_RAW', data)
            resolve(data)
          })
          .catch(error => {
            reject(error)
          })
      })
    },

    // 今日已结
    async MemberOrdersBalanced({ commit, state }, payload) {
      return new Promise((resolve, reject) => {
        ordersBalanced(payload)
          .then(data => {
            console.log('获取今日已结', data)
            commit('MEMBER_SET_BALANCED', data)
            resolve(data)
          })
          .catch(error => {
            reject(error)
          })
      })
    },

    // 获取两周报表
    async MemberOrdersHistory({ commit, state }, payload) {
      return new Promise((resolve, reject) => {
        ordersHistory(payload)
          .then(data => {
            commit('MEMBER_SET_HISTORY', data)
            resolve(data)
          })
          .catch(error => {
            reject(error)
          })
      })
    },

    // 会员投币
    async MemberBet({ commit, state }, payload) {
      return new Promise((resolve, reject) => {
        bet(payload)
          .then(data => {
            resolve(data)
          })
          .catch(error => {
            reject(error)
          })
      })
    },

    // 游戏规则
    async MemberGameRule({ commit, state }, payload) {
      return new Promise((resolve, reject) => {
        gameRule(payload)
          .then(data => {
            commit('MEMBER_SET_RULE', data)
            resolve(data)
          })
          .catch(error => {
            reject(error)
          })
      })
    },

    // 最新结果
    async MemberLastResult({ commit, state }, payload) {
      return new Promise((resolve, reject) => {
        console.log('what`s payload', payload)
        lastResult(payload)
          .then(data => {
            commit('MEMBER_SET_LAST_RESULT', data)
            resolve(data)
          })
          .catch(error => {
            reject(error)
          })
      })
    },

    // 最新注单
    async MemberLastOrder({ commit, state }, payload) {
      return new Promise((resolve, reject) => {
        lastOrder(payload)
          .then(data => {
            console.log('获取最新注单结果', data)
            commit('MEMBER_SET_LAST_ORDER', data)
            resolve(data)
          })
          .catch(error => {
            reject(error)
          })
      })
    },
    // 开奖结果
    async Lotteryresults({ commit, state }, payload) {
      return new Promise((resolve, reject) => {
        result(payload)
          .then(data => {
            commit('LOTTERY_RESULE_AA', data)
            resolve(data)
          })
          .catch(error => {
            reject(error)
          })
      })
    },
  },
}
const formatLottery = (lottery) => {
  for (const key in lottery) {
    if (lottery.hasOwnProperty(key)) {
      const element = lottery[key]
      element.forEach(row => {
        row['checked'] = false // 勾选
        row['rechecked'] = true // 再次确认
        row['amount'] = ''
      })
    }
  }
  return lottery
}

export default member
